package cn.congzhou.crm.service.impl;

import cn.congzhou.crm.domain.Department;
import cn.congzhou.crm.exception.ProhibitDeleteException;
import cn.congzhou.crm.mapper.DepartmentMapper;
import cn.congzhou.crm.mapper.EmployeeMapper;
import cn.congzhou.crm.query.QueryObject;
import cn.congzhou.crm.service.IDepartmentService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DepartmentServiceImpl implements IDepartmentService {

    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private DepartmentMapper departmentMapper;

    @Override
    public int deleteByPrimaryKey(Long id) {
        if(id!=null){
            departmentMapper.deleteByPrimaryKey(id);
        }
        return 0;
    }


    @Override
    public Department selectByPrimaryKey(Long id) {
        Department dept = departmentMapper.selectByPrimaryKey(id);
        return dept;
    }

    @Override
    public List<Department> selectAll() {
        List<Department> dept = departmentMapper.selectAll();
        return dept;
    }

    @Override
    public void saveOrUpdate(Department dept) {
        if(dept.getId()!=null){
            departmentMapper.updateByPrimaryKey(dept);
        }else {
            departmentMapper.insert(dept);
        }
    }

    @Override
    public PageInfo<Department> selectByPage(QueryObject qo) {
//      调用这个类的静态方法处理分页数据
        PageHelper.startPage(qo.getCurrentPage(),qo.getPageSize());
        List<Department> list = departmentMapper.selectByPage(qo);
//      创建页面信息对象封装起来
        PageInfo<Department> pageInfo = new PageInfo<>(list);
        return pageInfo;
    }

    @Override
    public void batchDeleteDepartment(Long[] ids) {
        if(ids != null && ids.length > 0){
            int count = employeeMapper.checkEmpCountByDeptIds(ids);
            if(count > 0){
                throw new ProhibitDeleteException("选中的部门中存在员工，不可以删除，请先清除部门下的员工");
            }
            departmentMapper.batchDeleteDepartment(ids);
        }
    }
}
